package com.easytake.emotioncat.fileio;

import com.easytake.emotioncat.fileio.minio.MinioConfig;
import com.easytake.emotioncat.fileio.minio.MinioUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Component
public class FileUtil {
    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private MinioConfig prop;

    /**
     * 保存文件
     *
     * @param files
     * @return
     */
    public String upload(MultipartFile[] files) {
        List<String> pathList = new ArrayList<>();
        for (MultipartFile file : files) {
            pathList.add(upload(file));
        }
        return String.join(";", pathList);
    }


    /**
     * 保存文件
     *
     * @param file
     * @return
     */
    public String upload(MultipartFile file) {
        String objectName = minioUtil.upload(file);
        if (null != objectName) {
            return objectName;
        }
        throw new RuntimeException("文件上传失败");
    }

    /**
     * 补充地址前缀
     *
     * @param path
     * @return
     */
    public String generateFileUrl(String path) {
        return prop.getEndpoint() + "/" + prop.getBucketName() + "/" + path;
    }

    public void downLoad(String fileName, HttpServletResponse res) {
        minioUtil.download(fileName, res);
    }

    /**
     * 删除文件
     *
     * @param url
     */
    public void remove(String path) {
        if (StringUtils.isBlank(path)) {
            return;
        }
        minioUtil.remove(path);
    }
}
